import path from 'node:path';

import NutUIResolver from '@nutui/auto-import-resolver';
import Vue from '@vitejs/plugin-vue';
import VueJSX from '@vitejs/plugin-vue-jsx';
import UnoCSS from 'unocss/vite';
import AutoImport from 'unplugin-auto-import/vite';
import { FileSystemIconLoader } from 'unplugin-icons/loaders';
import Icons from 'unplugin-icons/vite';
import { VueUseComponentsResolver } from 'unplugin-vue-components/resolvers';
import AutoComponents from 'unplugin-vue-components/vite';
import { VueRouterAutoImports } from 'unplugin-vue-router';
import VueRouter from 'unplugin-vue-router/vite';
import { defineConfig } from 'vite';
import { viteExternalsPlugin } from 'vite-plugin-externals';
import { viteStaticCopy } from 'vite-plugin-static-copy';

import { svgTransform } from './internals/svgTransform';
import { createProxy } from './vite.proxy';

// https://vitejs.dev/config/
export default defineConfig((config) => {
	return {
		resolve: {
			alias: {
				'@': path.resolve('./src'),
			},
			extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
		},
		define: {
			CESIUM_BASE_URL: JSON.stringify('./Cesium/'),
		},
		server: {
			port: 3201,
			proxy: createProxy(config),
		},
		plugins: [
			VueRouter({
				routesFolder: 'src/pages',
				exclude: ['./**/components'],
			}),
			Vue({}),
			VueJSX(),
			UnoCSS(),
			Icons({
				autoInstall: true,
				customCollections: {
					custom: FileSystemIconLoader('./icons', (svg) => {
						return svgTransform(svg, { varColor: true, varPrefix: 'custom' });
					}),
				},
			}),

			viteExternalsPlugin({
				cesium: 'Cesium',
			}),
			viteStaticCopy({
				targets: [
					{
						src: 'node_modules/cesium/Build/Cesium/Workers/**',
						dest: 'Cesium/Workers',
					},
					{
						src: 'node_modules/cesium/Build/Cesium/ThirdParty/**',
						dest: 'Cesium/ThirdParty',
					},
					{
						src: 'node_modules/cesium/Build/Cesium/Assets/**',
						dest: 'Cesium/Assets',
					},
					{
						src: 'node_modules/cesium/Build/Cesium/Widgets/**',
						dest: 'Cesium/Widgets',
					},
					{
						src: 'node_modules/cesium/Build/CesiumUnminified/Cesium.js',
						dest: 'Cesium/',
					},
				],
			}),
			AutoImport({
				dts: 'autoimports.d.ts',
				resolvers: [NutUIResolver()],
				imports: [
					'vue',
					'pinia',
					// 'vue-router',
					VueRouterAutoImports,
					'@vueuse/core',
					{
						axios: [['default', 'axios']],
					},
					{
						echarts: [['*', 'echarts']],
					},
					{
						'@turf/turf': [['*', 'turf']],
					},
				],
			}),
			// 组件自动引入
			AutoComponents({
				dts: 'components.d.ts',
				dirs: ['src/components', 'src/layout', 'src/business'],
				resolvers: [NutUIResolver(), VueUseComponentsResolver()],
			}),
		],
	};
});
